package com.wgq.TestScript;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileReader;
import java.net.URL;

//java  与脚本之间的交互
public class TestScript {


    public static void main(String[] args) throws Exception {
        //获得脚本引擎对象
        ScriptEngineManager sc = new ScriptEngineManager();
        ScriptEngine engine =sc.getEngineByName("javascript");

        //定义变量存储到引擎上下文
        engine.put("msg","八千里路云和月");
        String str = "var user={name:'王',age:18,school:['清华','北大']};";
        str+="print(user.name);";


        //执行脚本
        engine.eval(str);

        //修改js参数
        engine.eval("msg = '三十功名尘与土'");
        //通过java获取JavaScript参数
        System.out.println(engine.get("msg"));

        System.out.println("--------------------------------------------------");

        //定义函数
        engine.eval("function add(a,b){var sum = a+b; return sum;}");

        //执行函数
        Invocable  jsin = (Invocable) engine;
        Object re =  jsin.invokeFunction("add",new Object[]{13,21});
        System.out.println(re);

        //调用执行js脚本文件,文件要在项目src下
        URL url = TestScript.class.getClassLoader().getResource("com/wgq/TestScript/script.js");
        FileReader fe = new FileReader(url.getPath());
        engine.eval(fe);
        fe.close();
    }
}
